package com.ibm.db2oncampus.portal.framework.orm.hibernate.support;

import java.util.List;

import org.hibernate.FlushMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.springframework.dao.DataAccessException;

import com.ibm.db2oncampus.portal.framework.persistence.Dao;

/**
 * 
 * @author Wellington
 *
 */
public abstract class HibernateDaoSupport<T> extends org.springframework.orm.hibernate3.support.HibernateDaoSupport
	implements Dao<T> {

	private Class<T> persistentClass;
	
	public HibernateDaoSupport() {
	}

	public T findById(long id) throws DataAccessException {
		return (T) getHibernateTemplate().get(getPersistentClass(), Long.valueOf(id));
	}

	public List<T> findAll() throws DataAccessException {
		return (List<T>) getHibernateTemplate().loadAll(getPersistentClass());
	}

	public List<T> findAll(String columOrder) throws DataAccessException {
		DetachedCriteria criteria = DetachedCriteria.forClass(getPersistentClass());
		criteria.addOrder(Order.asc(columOrder));
		return (List<T>) getHibernateTemplate().findByCriteria(criteria);
	}

	public void save(T entity) throws DataAccessException {
		getSession().setFlushMode(FlushMode.AUTO);
		getHibernateTemplate().saveOrUpdate(entity);
		getHibernateTemplate().flush();
	}

	public void remove(T entity) throws DataAccessException {
		getHibernateTemplate().delete(entity);
		getHibernateTemplate().flush();
	}

	public void removeAll(List<T> list) {
		getHibernateTemplate().deleteAll(list);
		getHibernateTemplate().flush();
	}

	public void setPersistentClass(Class<T> persistentClass) {
		this.persistentClass = persistentClass;
	}

	public Class<T> getPersistentClass() {
		return persistentClass;
	}
}